package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.WxOrderCommentBo;
import com.cskaoyan.bean.bo.WxOrderSubmitBo;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.bean.vo.wxorderlistvoentity.GoodsListEntity;
import com.cskaoyan.bean.vo.wxorderlistvoentity.HandleOptionEntity;
import com.cskaoyan.bean.vo.wxorderlistvoentity.OrderDetailGoodsEntity;
import com.cskaoyan.bean.vo.wxorderlistvoentity.OrderDetailInfoEntity;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Since 2022/12/29 14:00
 * @Author LA
 * @Description: OrderService实现类
 */
@Service
public class OrderServiceImp implements OrderService {
    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    ChannelMapper channelMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketAddressMapper MarketAddress;

    @Override
    public CommonData<AdminOrderListVo> list(BasePageInfo info, Short[] orderStatusArray, String orderId,
                                             Date start, Date end, Date[] timeArray,
                                             String userId, String orderSn) {
        // 开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        // 排序
        example.setOrderByClause(info.getSort() + " " + info.getOrder());
        MarketOrderExample.Criteria criteria = example.createCriteria();

        // 查询逻辑存在,表中deleted字段值为1是删除状态
        criteria.andDeletedEqualTo(false);
        // orderSn 订单编号
        if (!StringUtil.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        // userId 用户id
        if (!StringUtil.isEmpty(userId)) {
            int userIdInteger = Integer.parseInt(userId);
            criteria.andUserIdEqualTo(userIdInteger);
        }
        // orderStatusArray:订单状态 101 301
        if (orderStatusArray != null) {
            // short orderStatusArrayShort = Short.parseShort(orderStatusArray);
            // criteria.andOrderStatusEqualTo(orderStatusArrayShort);
            // 增加 订单状态多选
            List<Short> statusList = new ArrayList<>();
            for (Short ele : orderStatusArray) {
                statusList.add(ele);
            }
            criteria.andOrderStatusIn(statusList);
        }

        // start:2022-12-01 00:00:00 开始时间
        if (start != null && timeArray != null) {
            criteria.andAddTimeGreaterThanOrEqualTo(start);
        }
        // end: 2023-01-31 00:00:00  结束时间
        if (end != null && timeArray != null) {
            criteria.andAddTimeLessThanOrEqualTo(end);
        }
        // timeArray:数组内两个值 2022-12-01 00:00:00  2023-01-31 00:00:00

        // orderId 订单id号 ，匹配的是/detail接口


        // 调用mapper中的方法返回 相应类型的数据
        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);
        // 获取分页信息
        PageInfo pageInfo = new PageInfo<>(marketOrders);
        // 填充data返回
        return CommonData.data(pageInfo);
    }

    @Override
    public void delete(Integer orderId) {

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        // 删除状态置为1
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(new Date());
        // 通过id 更新删除状态和 更新时间
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public String selectCommentById(Integer id) {
        MarketComment marketComment = null;
        String getAdminContent = null;
        if (id != null) {
            marketComment = commentMapper.selectByPrimaryKey(id);
            getAdminContent = marketComment.getAdminContent();
        }
        // 拿到对象中的 评论信息
        return getAdminContent;
    }

    @Override
    public void updateCommentById(Integer id, String adminContent) {
        MarketComment marketComment = new MarketComment();
        marketComment.setId(id);
        marketComment.setAdminContent(adminContent);
        // 新增，更新时间 2023/1/02 1:55  add By la
        marketComment.setUpdateTime(new Date());
        // 更新 comment表 的adminContent
        commentMapper.updateByPrimaryKeySelective(marketComment);
    }

    @Override
    public OrderDetailVo detail(String idStr) {
        // 此id 为order的ID
        // 分别查出数据 进行填值
        // MarketOrder order;通过id查
        int id = Integer.parseInt(idStr);
        MarketOrder order = orderMapper.selectByPrimaryKey(id);
        // MarketOrder order = orderMapper.selectByPrimaryKey(id);
        Integer userId = order.getUserId();
        // MarketUser user; 通过userId查
        MarketUser user = null;
        if (userId != null) {
            user = userMapper.selectByPrimaryKey(userId);
        }
        // MarketUserExample marketUserExample = new MarketUserExample();
        // MarketUserExample.Criteria criteria1 = marketUserExample.createCriteria();
        // if (userId!=null) {
        //     criteria1.andIdEqualTo(userId);
        // }
        // List<MarketUser> users = userMapper.selectByExample(marketUserExample);
        // MarketUser user = users.get(0);

        // List<MarketOrderGoods> orderGoods;通过orderId查
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        if (!StringUtil.isEmpty(idStr)) {
            criteria.andOrderIdEqualTo(id);
        }
        // if (id != null) {
        //     criteria.andOrderIdEqualTo(id);
        // }
        List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        // 创建用于返回的对象并赋值
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setUser(user);
        orderDetailVo.setOrderGoods(orderGoodsList);
        return orderDetailVo;
    }

    @Override
    public void ship(Integer orderId, String shipChannel, String shipSn) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setShipChannel(shipChannel);
        marketOrder.setShipSn(shipSn);
        // 发货时间
        marketOrder.setShipTime(new Date());
        // 退款之后,状态变更为:'301: '已发货'
        short shipStatus = 301;
        marketOrder.setOrderStatus(shipStatus);
        // 更新发货信息
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void refund(Integer id, BigDecimal refundMoney) {
        // 通过orderid查询 实付金额
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(id);
        BigDecimal actualPrice = marketOrder.getActualPrice();
        // 装载 退款信息的 对象
        MarketOrder marketOrderUpdate = new MarketOrder();
        marketOrderUpdate.setId(id);
        marketOrderUpdate.setRefundAmount(actualPrice);
        marketOrderUpdate.setRefundType("后台退");
        marketOrderUpdate.setRefundTime(new Date());
        // 退款之后,状态变更为:203: '已退款'
        short refundStatus = 203;
        marketOrderUpdate.setOrderStatus(refundStatus);
        // 更新 退款信息
        orderMapper.updateByPrimaryKeySelective(marketOrderUpdate);

    }

    @Override
    public List<MarketLogisticsChannel> channel() {
        List<MarketLogisticsChannel> list = channelMapper.selectAll();
        return list;
    }

    /**
     * @description: 根据主键查询订单
     * @param: id
     * @return: com.cskaoyan.bean.MarketOrder
     * @author: JianhuaZeng
     * @date: 2022/12/31 2022/12/31
     */
    public MarketOrder queryOrderById(Integer id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    // @Override
    // public void updateUserCommentByObj(WxOrderCommentBo wxOrderCommentBo) {
    //     MarketComment marketComment = new MarketComment();
    //
    //     // 装载对象信息
    //     marketComment.setId(wxOrderCommentBo.getOrderGoodsId());
    //     marketComment.setContent(wxOrderCommentBo.getContent());
    //     marketComment.setStar(wxOrderCommentBo.getStar());
    //     marketComment.setHasPicture(wxOrderCommentBo.getHasPicture());
    //     marketComment.setPicUrls(wxOrderCommentBo.getPicUrls());
    //     // 新增时间 和更新时间
    //     marketComment.setAddTime(new Date());
    //     marketComment.setUpdateTime(new Date());
    //     // 更新 comment表 的adminContent
    //     commentMapper.updateByPrimaryKeySelective(marketComment);
    //
    // }

    /**
     * 微信小程序的的list展示
     *
     * @param showType
     * @param info
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.vo.WxOrderListVo>
     * @author LA
     * @since 2023/01/02 2:43
     */
    @Override
    public CommonData<WxOrderListVo> wxList(Short showType, BasePageInfo info) {
        // 开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());

        MarketOrderExample example = new MarketOrderExample();
        // // 先判空，再进行排序
        // if (!StringUtil.isEmpty(info.getSort()) && !StringUtil.isEmpty(info.getOrder())) {
        //     example.setOrderByClause(info.getSort() + " " + info.getOrder());
        // }
        //
        MarketOrderExample.Criteria criteria = example.createCriteria();
        // // 按照时间，排序
        // example.setOrderByClause("add_time desc");
        // 查询逻辑存在,表中deleted字段值为1是删除状态
        criteria.andDeletedEqualTo(false);

        List<Short> statusList = getStatusListByShowType(showType);
        criteria.andOrderStatusIn(statusList);
        // modify by LA 2023/01/03 15：12
        //  按照 更新时间 降序排序
        example.setOrderByClause("update_time desc");

        // 调用mapper中的方法返回 相应类型的数据
        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);

        /// 此处markOrder的list 要转成 WxOrderListVo 的list
        ArrayList<WxOrderListVo> wxOrderListVos = new ArrayList<>();
        for (MarketOrder order : marketOrders) {
            // 拿到每一个 MarketOrder对象,并转成WxOrderListVo对象
            WxOrderListVo wxOrderListVo = new WxOrderListVo();
            // 拿到订单的id
            Integer orderId = order.getId();
            //  拿到订单的状态并处理
            Short orderStatus = order.getOrderStatus();
            String orderStatusText = getOrderStatusTextByOrderStatus(orderStatus);
            // wxOrderList对象装载
            wxOrderListVo.setId(orderId);
            wxOrderListVo.setOrderStatusText(orderStatusText);
            wxOrderListVo.setActualPrice(order.getActualPrice());
            wxOrderListVo.setOrderSn(order.getOrderSn());
            // 团购标志，默认false
            wxOrderListVo.setGroupin(false);
            // 售后标志
            wxOrderListVo.setAftersaleStatus(((short) 0));
            // 调用方法填充handleOption，订单操作状态对象
            HandleOptionEntity handleOptionEntity = getHandleOptionEntityByOrder(order);
            wxOrderListVo.setHandleOption(handleOptionEntity);
            // 填充 goodsList，订单中商品列表信息
            List<GoodsListEntity> goodsListEntityList = orderGoodsMapper.selectGoodsEntityByOrderId(orderId);
            wxOrderListVo.setGoodsList(goodsListEntityList);
            // 每循环一次 就把老list中的元素 转成的新元素填充至新list中
            wxOrderListVos.add(wxOrderListVo);
        }
        // 循环结束wxOrderListVos 填充完毕
        // 获取分页信息
        PageInfo pageInfo = new PageInfo<>(wxOrderListVos);
        // 填充data返回
        return CommonData.data(pageInfo);
    }

    /**
     * 抽出方法：订单状态code转字符串描述
     *
     * @param orderStatus
     * @return java.lang.String
     * @author LA
     * @since 2023/01/02 11:21
     */
    private String getOrderStatusTextByOrderStatus(Short orderStatus) {
        String orderStatusText = null;
        switch (orderStatus) {
            case 101:
                // 待付款
                orderStatusText = "待付款";
                break;
            case 201:
                // 待发货
                orderStatusText = "待发货";
                break;
            case 301:
                // 待收货
                orderStatusText = "待收货";
                break;
            case 401:
                // 待评价
                orderStatusText = "待评价";
                break;
            case 402:
                // 待评价
                orderStatusText = "待评价";
                break;
            default:
                orderStatusText = "全部";
        }
        return orderStatusText;
    }


    /**
     * 抽出方法：通过showType展示类别，填充其对应的orderStatusList
     *
     * @param showType
     * @return java.util.List<java.lang.Short>
     * @author LA
     * @since 2023/01/02 11:12
     */
    private List<Short> getStatusListByShowType(Short showType) {
        // 根据showtype，匹配不同的订单状态的信息
        List<Short> statusList = new ArrayList<>();
        switch (showType) {
            case 1:
                // 待付款
                statusList.add(((short) 101));
                break;
            case 2:
                // 待发货
                statusList.add(((short) 201));
                break;
            case 3:
                // 待收货
                statusList.add(((short) 301));
                break;
            case 4:
                // 待评价
                statusList.add(((short) 401));
                statusList.add(((short) 402));
                break;
            default:
                // 全部订单状态：
                // *  101: '未付款',
                // *  102: '用户取消',103: '系统取消',
                // *  201: '已付款',
                // *  202: '申请退款', 203: '已退款',
                // *  301: '已发货',
                // *  401: '用户收货', 402: '系统收货'
                statusList.add(((short) 101));
                statusList.add(((short) 102));
                statusList.add(((short) 103));
                statusList.add(((short) 201));
                statusList.add(((short) 202));
                statusList.add(((short) 203));
                statusList.add(((short) 301));
                statusList.add(((short) 401));
                statusList.add(((short) 402));
        }
        return statusList;
    }

    /**
     * 抽的方法：通过MarketOrder类对象， 获取其HandleOption
     * 更改判断逻辑 : modify by LA 2023/01/02 22:36
     *
     * @param order
     * @return com.cskaoyan.bean.vo.wxorderlistvoentity.HandleOptionEntity
     * @author LA
     * @since 2023/01/02 11:08
     */
    private HandleOptionEntity getHandleOptionEntityByOrder(MarketOrder order) {
        // 填充 handleOption，订单可以操作的 操作行为是什么?
        HandleOptionEntity handleOptionEntity = new HandleOptionEntity();
        Short orderStatus = order.getOrderStatus();
        // 确认   仅(已发货)待收货状态-->有确认收货
        if (orderStatus == 301) {
            handleOptionEntity.setConfirm(true);
        } else {
            handleOptionEntity.setConfirm(false);
        }
        // 取消   仅付款订单有取消订单按钮
        if (orderStatus == 101) {
            handleOptionEntity.setCancel(true);
        } else {
            handleOptionEntity.setCancel(false);
        }
        // 回购  收货之后可以回购
        if (orderStatus == 401 || orderStatus == 402) {
            handleOptionEntity.setRebuy(true);
        } else {
            handleOptionEntity.setRebuy(false);
        }
        // 支付   待付款的订单可以付款
        if (orderStatus == 101) {
            handleOptionEntity.setPay(true);
        } else {
            handleOptionEntity.setPay(false);
        }
        // 评价  TODO:订单状态为待评价,且没有评价内容orderGoods的可以评价
        if (orderStatus == 401 || orderStatus == 402) {
            handleOptionEntity.setComment(true);
        } else {
            handleOptionEntity.setComment(false);
        }
        // 删除  待评价的订单可以删除
        if (orderStatus == 401 || orderStatus == 402) {
            handleOptionEntity.setDelete(true);
        } else {
            handleOptionEntity.setDelete(false);
        }
        // 售后   待评价可以的申请售后
        if (orderStatus == 401 || orderStatus == 402) {
            handleOptionEntity.setAftersale(((short) 1));
        } else {
            handleOptionEntity.setAftersale(((short) 0));
        }
        // 退款  待发货的可以申请退款
        if (orderStatus == 201) {
            handleOptionEntity.setRefund(true);
        } else {
            handleOptionEntity.setRefund(false);
        }
        return handleOptionEntity;
    }

    /**
     * 微信小程序 订单list 中的详情信息
     *
     * @param id 订单表的id，goods表的orderId
     * @return com.cskaoyan.bean.vo.WxOrderDetailVo
     * @author LA
     * @since 2023/01/02 10:49
     */
    @Override
    public WxOrderDetailVo wxDetail(String id) {
        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        // 查询逻辑存在,表中deleted字段值为1是删除状态
        criteria.andDeletedEqualTo(false);
        // 通过orderId,查到的order表的数据
        Integer orderId = Integer.parseInt(id);
        criteria.andIdEqualTo(orderId);
        MarketOrder orderSrc = orderMapper.selectByPrimaryKey(orderId);
        // 创造用于返回的对象
        WxOrderDetailVo wxOrderDetail = new WxOrderDetailVo();
        // wxOrderDetail填值
        // 订单信息  OrderDetailInfoEntity orderInfo;
        OrderDetailInfoEntity orderInfo = new OrderDetailInfoEntity();
        BeanUtils.copyProperties(orderSrc, orderInfo);
        // 订单状态文本描述
        orderInfo.setOrderStatusText(getOrderStatusTextByOrderStatus(orderSrc.getOrderStatus()));
        // 操作标志对象填充
        orderInfo.setHandleOption(getHandleOptionEntityByOrder(orderSrc));
        // 快递信息相关
        // expCode: "YTO"
        // expName: "圆通速递"
        // expNo: "22
        String expCode = orderSrc.getShipChannel();
        String expName = null;
        // 报错： java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
        if (!StringUtil.isEmpty(expCode)) {
            expName = orderMapper.selectExpNoByName(expCode);
        }
        orderInfo.setExpCode(expCode);
        orderInfo.setExpName(expName);
        orderInfo.setExpNo(orderSrc.getShipSn());
        //
        wxOrderDetail.setOrderInfo(orderInfo);
        // 快递信息
        String[] expressInfo = {orderSrc.getShipChannel()};
        wxOrderDetail.setExpressInfo(expressInfo);
        // 订单内商品信息，需要private List<OrderDetailGoodsEntity> orderGoods;
        // 通过orderId查
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteriaGoods = orderGoodsExample.createCriteria();
        if (orderId != null) {
            criteriaGoods.andOrderIdEqualTo(orderId);
        }
        List<MarketOrderGoods> orderGoodsListSrc = orderGoodsMapper.selectByExample(orderGoodsExample);
        //  List<MarketOrderGoods> 转成需要的List<OrderDetailGoodsEntity>
        List<OrderDetailGoodsEntity> orderDetailGoods = new ArrayList<>();
        for (MarketOrderGoods goods : orderGoodsListSrc) {
            // goods取值给 goodsEntity
            OrderDetailGoodsEntity goodsEntity = new OrderDetailGoodsEntity();

            goodsEntity.setProductId(goods.getProductId());
            goodsEntity.setAddTime(goods.getAddTime());
            goodsEntity.setOrderId(goods.getOrderId());
            goodsEntity.setGoodsId(goods.getGoodsId());
            goodsEntity.setGoodsSn(goods.getGoodsSn());
            goodsEntity.setUpdateTime(goods.getUpdateTime());
            // 规格数组
            String[] specifications = goods.getSpecifications();
            goodsEntity.setSpecifications(specifications);

            goodsEntity.setNumber(goods.getNumber());
            goodsEntity.setPicUrl(goods.getPicUrl());
            goodsEntity.setDeleted(goods.getDeleted());
            goodsEntity.setPrice(goods.getPrice());
            goodsEntity.setComment(goods.getComment());
            goodsEntity.setId(goods.getId());
            goodsEntity.setGoodsName(goods.getGoodsName());
            // 每次循环 orderDetailGoods加一个对象
            orderDetailGoods.add(goodsEntity);
        }
        wxOrderDetail.setOrderGoods(orderDetailGoods);


        return wxOrderDetail;
    }

    @Override
    public Integer selectOrderGoodsCommentById(Integer goodsId) {
        Integer comment = null;
        if (goodsId != null) {
            MarketOrderGoods marketOrderGoods = orderGoodsMapper.selectByPrimaryKey(goodsId);
            // 拿到表中comment数据
            if (marketOrderGoods != null) {
                comment = marketOrderGoods.getComment();
            }
        }
        return comment;
    }

    @Override
    public void insertComment(WxOrderCommentBo wxOrderCommentBo) {
        // 取值
        int goodsId = wxOrderCommentBo.getOrderGoodsId();
        Boolean hasPicture = wxOrderCommentBo.getHasPicture();
        String content = wxOrderCommentBo.getContent();
        String[] picUrls = wxOrderCommentBo.getPicUrls();
        short star = wxOrderCommentBo.getStar();
        // 1.更新orderGoods表中的comment标志，其值对应的是comment表中的value_id
        MarketOrderGoods orderGoods = new MarketOrderGoods();
        orderGoods.setId(goodsId);
        // comment的代码值，每次都是表中comment的最大值加一
        Integer commentNum = orderGoodsMapper.selectMaxComment() + 1;
        orderGoods.setComment(commentNum);
        orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);

        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        // 2.comment表插入一条数据，用于记录用户的订单的商品的评价信息
        MarketComment record = new MarketComment();
        record.setUserId(userId);
        // record.setUserId(1);

        record.setValueId(commentNum);
        byte type = 0;
        record.setType(type);
        record.setContent(content);
        record.setHasPicture(hasPicture);
        record.setPicUrls(picUrls);
        record.setStar(star);
        record.setAddTime(new Date());
        record.setUpdateTime(new Date());
        record.setDeleted(false);
        if (record != null) {
            commentMapper.insertSelective(record);
        }
        // 3.order表的comment（待评价商品数量）数字减1 todo
        // 先查出 订单对应有几个待评价商品，
        // 通过orderid 查orderGoods
        // 减一
    }

    @Override
    public MarketOrderGoods wxGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoods orderGoods = orderGoodsMapper.selectByOrderIDAndGoodsID(orderId, goodsId);
        return orderGoods;
    }

    @Override
    public void wxDelete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        // 删除状态置为1
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(new Date());
        // 通过id 更新删除状态和 更新时间
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void wxRefund(Integer orderId) {
        // 更新order表 订单状态
        // 装载 退款信息的 对象
        MarketOrder marketOrderUpdate = new MarketOrder();
        marketOrderUpdate.setId(orderId);
        marketOrderUpdate.setUpdateTime(new Date());
        // 用户申请退款
        short newStatus = 202;
        marketOrderUpdate.setOrderStatus(newStatus);
        // 更新 退款信息
        orderMapper.updateByPrimaryKeySelective(marketOrderUpdate);
    }

    @Override
    public void wxCancel(Integer orderId) {
        MarketOrder marketOrderUpdate = new MarketOrder();
        marketOrderUpdate.setId(orderId);
        marketOrderUpdate.setUpdateTime(new Date());
        // 用户取消
        short newStatus = 102;
        marketOrderUpdate.setOrderStatus(newStatus);
        // 更新 取消信息
        orderMapper.updateByPrimaryKeySelective(marketOrderUpdate);
    }

    @Override
    public void wxConfirm(Integer orderId) {
        MarketOrder marketOrderUpdate = new MarketOrder();
        marketOrderUpdate.setId(orderId);
        marketOrderUpdate.setUpdateTime(new Date());
        // 用户收货
        short newStatus = 401;
        marketOrderUpdate.setOrderStatus(newStatus);
        // 更新 取消信息
        orderMapper.updateByPrimaryKeySelective(marketOrderUpdate);
    }

    @Override
    public WxOrderSubmitVo wxSubmit(WxOrderSubmitBo orderSubmitBo/*, HttpSession session*/) {
        // 判空 参数空直接返回空
        if (orderSubmitBo == null) {
            return null;
        }
        // 从session域中获取数据
        // Integer cartId = (Integer) session.getAttribute("cartId");
        // Integer addressId = (Integer) session.getAttribute("addressId");
        // Integer couponId = (Integer) session.getAttribute("couponId");
        // Integer userCouponId = (Integer) session.getAttribute("userCouponId");
        // Integer grouponRulesId = (Integer) session.getAttribute("grouponRulesId");
        // // 判断请求参数的值 和session域中的拿到的是否相等
        // if (cartId != orderSubmitBo.getCartId() || addressId != orderSubmitBo.getAddressId()
        //         || couponId != orderSubmitBo.getCouponId() || userCouponId != orderSubmitBo.getUserCouponId()
        //         || grouponRulesId != orderSubmitBo.getGrouponRulesId()) {
        //     return null;
        // }


        // 1.order表 插值
        MarketOrder order = new MarketOrder();
        // //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        if (userId != null) {
            // 默认取1吧
            order.setUserId(1);
        } else {
            order.setUserId(userId);
        }
        // 用户id 和checkd =1 表示为 选中的数据
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        criteria.andCheckedEqualTo(true);
        List<MarketCart> cartsList = cartMapper.selectByExample(example);
        MarketCart marketCart = cartsList.get(0);
        // 已经拿到购物车数据，进行 对象填值
        // 订单 实际总金额
        BigDecimal getNumber = new BigDecimal(marketCart.getNumber());
        BigDecimal actualPrice = marketCart.getPrice().multiply(getNumber);
        // 运费
        BigDecimal freightPrice = new BigDecimal(0);
        // 优惠券数目
        // 优惠券的金额  couponPrice
        BigDecimal couponPrice = new BigDecimal(0);
        // 商品规格详情 todo
        String specifications = marketCart.getSpecifications();
        // 通过userid
        MarketAddressExample example1 = new MarketAddressExample();
        MarketAddressExample.Criteria criteria1 = example1.createCriteria();
        if (userId != null) {
            criteria1.andUserIdEqualTo(userId);
        }
        List<com.cskaoyan.bean.MarketAddress> marketAddressesList = MarketAddress.selectByExample(example1);
        com.cskaoyan.bean.MarketAddress address = marketAddressesList.get(0);

        // 填充order对象
        // 时间
        order.setAddTime(new Date());
        order.setUpdateTime(new Date());
        // 金额
        order.setActualPrice(actualPrice);
        order.setGoodsPrice(marketCart.getPrice());
        order.setFreightPrice(freightPrice);
        order.setCouponPrice(couponPrice);
        order.setOrderPrice(actualPrice.subtract(couponPrice));
        // 地址信息相关
        order.setAddress(address.myToAddressString());

        order.setConsignee(address.getName());
        order.setMobile(address.getTel());
        // 留言
        order.setMessage(orderSubmitBo.getMessage());

        // orderSn 为当前最大值加 1
        Long orderSn = orderMapper.selectMaxOrderSn() + 1;
        order.setOrderSn(String.valueOf(orderSn));
        // 更新为待付款状态
        // 用户付款状态更新
        short newStatus = 101;
        order.setOrderStatus(newStatus);
        BigDecimal zeroPrice = new BigDecimal(0);
        order.setIntegralPrice(zeroPrice);
        order.setGrouponPrice(zeroPrice);
        // 调用方法，对象有选择的插入数据库order表

        orderMapper.insertSelective(order);
        // 拿到自增的主键
        Integer orderId = order.getId();
        // 2.orderGoods表 插值
        MarketOrderGoods orderGoods = new MarketOrderGoods();
        // for (CartListBean goodsEle : checkedGoodsList) {
        // 每次循环，重新填充orderGoods对象
        orderGoods.setOrderId(orderId);
        orderGoods.setGoodsId(marketCart.getGoodsId());
        orderGoods.setGoodsSn(marketCart.getGoodsSn());
        orderGoods.setProductId(marketCart.getProductId());
        orderGoods.setNumber(marketCart.getNumber());
        orderGoods.setPrice(marketCart.getPrice());
        // private List<String> specifications 需要转 String[] specifications
        // List<String> list = goodsEle.getSpecifications();
        // String[] setSpecifications = list.toArray(new String[list.size()]);
        //
        String[] spec = {marketCart.getSpecifications()};
        orderGoods.setSpecifications(spec);
        orderGoods.setPicUrl(marketCart.getPicUrl());
        // 时间
        orderGoods.setAddTime(new Date());
        orderGoods.setUpdateTime(new Date());
        // 每次用新填充的对象进行插入操作
        // 每循环一次，都会往orderGoods表查一条记录
        // 循环结束，订单对应的商品详细信息插表完毕
        orderGoodsMapper.insertSelective(orderGoods);
        //
        // 购物车清空忘了 todo

        // 结果响应
        WxOrderSubmitVo wxOrderSubmitVo = new WxOrderSubmitVo();
        wxOrderSubmitVo.setOrderId(orderId);
        wxOrderSubmitVo.setGrouponLinkId(0);
        return wxOrderSubmitVo;
    }

    @Override
    public void wxPrepay(Integer orderId) {
        MarketOrder marketOrderUpdate = new MarketOrder();
        marketOrderUpdate.setId(orderId);
        marketOrderUpdate.setUpdateTime(new Date());
        // 支付相关
        // 编号 暂定写死值
        marketOrderUpdate.setPayId("100001");
        marketOrderUpdate.setPayTime(new Date());
        // 用户付款状态更新
        short newStatus = 201;
        // 更新时间更新
        marketOrderUpdate.setOrderStatus(newStatus);

        // 更新 付款信息
        orderMapper.updateByPrimaryKeySelective(marketOrderUpdate);
    }

}


